package cetcbigdata.da.service.guangdong.powers;

import cetcbigdata.da.base.Base;
import com.alibaba.datax.common.plugin.RecordSender;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class GuangDong extends Base {
    private static String baseRegion = "广东省";

    private static String baseModule = "服务事项-权责清单";


    @Override
    public JSONObject getDataDemo() {
        try {
            return processResult("xxx", "xxx", "xxx", "xxx", new JSONObject(), "ss", "ss");
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void getData(RecordSender recordSender, List<Object> fieldsList) {
        try {
            for(JSONObject r : getRegion()){
                for(JSONObject m : getModule()){
                    this.parseListPage(recordSender, fieldsList, r, m);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private JSONObject parseListPage(RecordSender recordSender, List<Object> fieldsList, JSONObject regionItem, JSONObject moduleItem){
        //获取各区编码和类型编码
        String regCode = regionItem.getString("code");
        String code =  moduleItem.getString("code");

        //获取各区名称和类型名称
        String module = baseModule + "-" + moduleItem.getString("name");
        String region = baseRegion + "-" + regionItem.getString("name");
        try{
            // 初始化总页码数
            int pages = 0;
            // 当前页
            int currentPage = 1;
            // 如果当前也不等于总页码数，则一直循环 ，实现翻页
            while (true){
                String listUrl = "https://www.gdzwfw.gov.cn/portal/api/v2/item-event/getPowerandresponsibility";
                JSONObject parmas = new JSONObject();
                parmas.put("AREACODE", regCode);
                parmas.put("DEPT_CODE", "");
                parmas.put("KEYWORD", "");
                parmas.put("TASK_TYPE", code);
                parmas.put("pageNum", currentPage);
                parmas.put("pageSize", 10);
                String listResponse =  postReq(listUrl, parmas);
                JSONObject responseObj = JSONObject.parseObject(listResponse);
                JSONArray listTemp = responseObj.getJSONArray("PowerandresponsibilityList");
                JSONObject listPageObj = new JSONObject();
                for(Object o : listTemp){
                    JSONObject item = (JSONObject) o;
                    String parentCatalogId = item.getString("CATALOG_ID");
                    if(listPageObj.containsKey(parentCatalogId)){
                        listPageObj.getJSONArray(parentCatalogId).add(item);
                    }else {
                        listPageObj.put(parentCatalogId, new JSONArray());
                        listPageObj.getJSONArray(parentCatalogId).add(item);
                    }
                }
                // 每页每项遍历
                for(String key : listPageObj.keySet() ){
                    JSONObject contentParent =new JSONObject();
                    String title = null;
                    List<JSONObject> contentList = new ArrayList<>();
                    String detailUrl = null;
                    String implementationUrl = null;
                    String contentResponse = null;
                    String implementationResponse = null;
                    for(Object o : listPageObj.getJSONArray(key)){
                        JSONObject item = (JSONObject) o;
                        JSONObject detailParmas = new JSONObject();
                        detailUrl = "https://www.gdzwfw.gov.cn/portal/api/v2/item-event/getPowerandresponsibilityxx";
                        detailParmas.put("ITEMGUID", item.getString("ROWGUID"));
                        detailParmas.put("DEPT_CODE", item.getString("DEPT_CODE"));
                        title = item.getString("TASK_NAME");

                        // 请求详情页
                        JSONObject contentChild =new JSONObject();
                        contentResponse = postReq(detailUrl, detailParmas);
                        JSONObject baseInfo = getBaseInfo(contentResponse);

                        //请求实施清单
                        implementationUrl = "https://www.gdzwfw.gov.cn/portal/api/v2/item/getCommonAuditItem";
                        JSONObject implementationParmas = new JSONObject();
                        implementationParmas.put("BASECODE", item.getString("CATALOG_ID"));
                        implementationParmas.put("DEPT_CODE", item.getString("DEPT_CODE"));
                        implementationParmas.put("TASK_TYPE", item.getString("TASK_TYPE"));
                        implementationParmas.put("pageNum", currentPage);
                        implementationParmas.put("pageSize", 10);


                        implementationResponse = postReq(implementationUrl, implementationParmas);
                        JSONArray implementationInfo = getimplementationList(implementationResponse);
                        contentChild.put("基本信息", baseInfo);
                        contentChild.put("实施清单", implementationInfo);
                        contentList.add(contentChild);
                    }

                    contentParent.put("名称", title);
                    contentParent.put("选项", contentList);
                    processResult(
                            listUrl, listResponse, detailUrl, contentResponse, contentParent,
                            region, module
                        );
                }
                //更新当前页
                currentPage = responseObj.getJSONObject("PAGEINFO").getInteger("CURRENTPAGEINDEX") + 1;
                // 更新总页数
                int total = responseObj.getJSONObject("PAGEINFO").getInteger("TOTALNUM");
                int size = responseObj.getJSONObject("PAGEINFO").getInteger("PAGESIZE");
                int prePages = total/size;
                pages = total%size == 0 ? prePages : prePages + 1;
                if (currentPage > pages){
                    break;
                }
            }
            return new JSONObject();
        }catch (Exception e){
            e.printStackTrace();
        }
        return new JSONObject();
    }

    private JSONObject getBaseInfo(String html){
        JSONObject base = new JSONObject();
        JSONObject response = JSONObject.parseObject(html);

        //基础信息
        JSONObject data =  response.getJSONObject("POWERANDRESPONSIBILITYLIST");
        base.put("行使主体", data.getString("DEPT_NAME"));
        base.put("编码", data.getString("XKSXBM"));
        base.put("依据", data.getString("LAWS"));
        base.put("责任事项", data.getString("RESPONSIBILITY"));
        //类别
        String taskType = data.getString("TASK_TYPE");
        switch (taskType){
            case "01" :
                base.put("类别", "行政许可");
                break;
            case "02" :
                base.put("类别", "行政处罚");
                break;
            case "03" :
                base.put("类别", "行政强制");
                break;
            case "04" :
                base.put("类别", "行政征收");
                break;
            case "05" :
                base.put("类别", "行政给付");
                break;
            case "06" :
                base.put("类别", "行政检查");
                break;
            case "07" :
                base.put("类别", "行政确认");
                break;
            case "08" :
                base.put("类别", "行政奖励");
                break;
            case "09" :
                base.put("类别", "行政裁决");
                break;
            case "20" :
                base.put("类别","其他类别");
                break;
            case "21":
                base.put("类别", "公共服务");
                break;



        }
        return base;

    }

    private JSONArray getimplementationList(String html){
        JSONArray implementationList = new JSONArray();
        JSONObject response = JSONObject.parseObject(html);

        JSONArray implementationOrg = response.getJSONArray("AUDIT_ITEMLIST");
        for (Object o : implementationOrg){
            JSONObject data = (JSONObject) o;
            JSONObject implementationdata = new JSONObject();
            implementationdata.put("服务事项名称", data.getString("CATANAME"));
            implementationdata.put("主管部门", data.getString("DEPT_NAME"));
            implementationdata.put("在线办理", data.getString("URL"));
            implementationdata.put("申请材料",
                    String.format("https://www.gdzwfw.gov.cn/portal/api/v2/item-event/getAuditItemDetailCur?TASK_CODE=%s",
                            data.getString("TASK_CODE")));
            implementationList.add(implementationdata);
        }
        return implementationList;
    }

    //获取市名和各市编码
    private static JSONArray getCityList(){
        String city = " [\n" +
                "{\"name\":\"广州市\",\"region\":\"440100\"},    \n" +
                "{\"name\":\"深圳市\",\"region\":\"440300\"}, \n" +
                "{\"name\":\"珠海市\",\"region\":\"440400\"},\n" +
                "{\"name\":\"汕头市\",\"region\":\"440500\"},\n" +
                "{\"name\":\"佛山市\",\"region\":\"440600\"},\n" +
                "{\"name\":\"韶关市\",\"region\":\"440200\"},\n" +
                "{\"name\":\"河源市\",\"region\":\"441600\"},\n" +
                "{\"name\":\"梅州市\",\"region\":\"441400\"},\n" +
                "{\"name\":\"惠州市\",\"region\":\"441300\"},\n" +
                "{\"name\":\"汕尾市\",\"region\":\"441500\"},\n" +
                "{\"name\":\"东莞市\",\"region\":\"441900\"},\n" +
                "{\"name\":\"中山市\",\"region\":\"442000\"},\n" +
                "{\"name\":\"江门市\",\"region\":\"440700\"},\n" +
                "{\"name\":\"阳江市\",\"region\":\"441700\"},\n" +
                "{\"name\":\"湛江市\",\"region\":\"440800\"},\n" +
                "{\"name\":\"茂名市\",\"region\":\"440900\"},\n" +
                "{\"name\":\"肇庆市\",\"region\":\"441200\"},\n" +
                "{\"name\":\"揭阳市\",\"region\":\"445200\"},\n" +
                "{\"name\":\"清远市\",\"region\":\"441800\"},\n" +
                "{\"name\":\"潮州市\",\"region\":\"445100\"},\n" +
                "{\"name\":\"云浮市\",\"region\":\"445300\"},\n" +
//                "{\"name\":\"横琴粤澳深度合作区\",\"region\":\"440405\"}\n" +
                " ]";
        return JSONArray.parseArray(city);
    }

    private static List<JSONObject> getRegion() {
        //获取各市编码
        JSONArray cityList = getCityList();
        List<JSONObject> out = new ArrayList<>();
        for (Object o : cityList){
            JSONObject oo = (JSONObject) o;
            String code = oo.getString("region");

            //请求获取各市包含的区的名称和编码
            String url = "https://www.gdzwfw.gov.cn/portal/custom-config/gdbsNav/getDetail";
            JSONObject header = new JSONObject();
            header.put("Referer", "https://apps.gdzwfw.gov.cn/");
            header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0");
            JSONObject params = new JSONObject();
            params.put("regCode", code);

            //获取各个市的所有区的源数据
            String response = postFormReq(url, header, params);
            JSONObject responseObj = JSONObject.parseObject(response);
            if (responseObj.getString("statusCode").equals("200")){
                JSONArray dataList = responseObj.getJSONObject("data").getJSONObject("data").getJSONArray("country");

                //判断各个市是否包含区
                if (dataList.size() != 0){
                    for (Object d : dataList){
                        JSONObject dd = (JSONObject) d;
                        JSONObject outItem = new JSONObject();
                        String name = oo.getString("name") + "-" + dd.getString("ORGSNAME");
                        outItem.put("name", name);
                        outItem.put("code", dd.getString("ORGAREACODE"));
                        out.add(outItem);
                    }
                }else {
                    JSONObject outItem = new JSONObject();
                    String name = oo.getString("name");
                    outItem.put("name", name);
                    outItem.put("code", oo.getString("region"));
                    out.add(outItem);
                }
            }
        }
        return out;
    }

    private static List<JSONObject> getModule(){
        //获取类型名称和编码
        String data = "{\"ITEMCOUNT\":[{\"COUNT\":\"270\",\"TASK_TYPE\":\"01\",\"TASK_TYPE_TEXT\":\"行政许可\"},{\"COUNT\":\"491\",\"TASK_TYPE\":\"02\",\"TASK_TYPE_TEXT\":\"行政处罚\"},{\"COUNT\":\"35\",\"TASK_TYPE\":\"03\",\"TASK_TYPE_TEXT\":\"行政强制\"},{\"COUNT\":\"3\",\"TASK_TYPE\":\"04\",\"TASK_TYPE_TEXT\":\"行政征收\"},{\"COUNT\":\"9\",\"TASK_TYPE\":\"05\",\"TASK_TYPE_TEXT\":\"行政给付\"},{\"COUNT\":\"29\",\"TASK_TYPE\":\"08\",\"TASK_TYPE_TEXT\":\"行政奖励\"},{\"COUNT\":\"42\",\"TASK_TYPE\":\"07\",\"TASK_TYPE_TEXT\":\"行政确认\"},{\"COUNT\":\"5\",\"TASK_TYPE\":\"09\",\"TASK_TYPE_TEXT\":\"行政裁决\"},{\"COUNT\":\"102\",\"TASK_TYPE\":\"06\",\"TASK_TYPE_TEXT\":\"行政检查\"},{\"COUNT\":\"171\",\"TASK_TYPE\":\"20\",\"TASK_TYPE_TEXT\":\"其他行政权力\"}]}";
        JSONArray validData = JSONObject.parseObject(data).getJSONArray("ITEMCOUNT");
        List<JSONObject> out = new ArrayList<>();
        for(Object o : validData){
            JSONObject oItem = (JSONObject) o;
            JSONObject outItem = new JSONObject();
            outItem.put("code", oItem.getString("TASK_TYPE"));
            outItem.put("name", oItem.getString("TASK_TYPE_TEXT"));
            out.add(outItem);
        }
        return out;
    }

    public static void main(String[] args) {
        GuangDong spiders = new GuangDong();
        spiders.getData(null, new ArrayList<>());
    }
}
